package com.edu.base.common.paytengjie.impl.wxapp.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;




/**
 * 微信工具类
 * @author ljf
 *
 */
public class WxUtil {

	
	/**
	 * 是否签名正确,规则是:按参数名称a-z排序,遇到空值的参数不参加签名。
	 * @return boolean
	 */
	public static boolean isTenpaySign(String characterEncoding, SortedMap<Object, Object> packageParams, String API_KEY) {
		StringBuffer sb = new StringBuffer();
		Set es = packageParams.entrySet();
		Iterator it = es.iterator();
		while(it.hasNext()) {
			Map.Entry entry = (Map.Entry)it.next();
			String k = (String)entry.getKey();
			String v = (String)entry.getValue();
			if(!"sign".equals(k) && null != v && !"".equals(v)) {
				sb.append(k + "=" + v + "&");
			}
		}
		
		sb.append("key=" + API_KEY);
		
		//算出摘要
		String mysign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toLowerCase();
		String tenpaySign = ((String)packageParams.get("sign")).toLowerCase();
		
		//System.out.println(tenpaySign + "    " + mysign);
		return tenpaySign.equals(mysign);
	}
	
	/**
	 * @Description： 生成随机字符串
	 * @author: lijiafu
	 * @since: 2015年7月23日 下午6:56:22
	 */
	public static String getNonceStr() {
		Random random = new Random();
		return MD5Util.MD5Encode(String.valueOf(random.nextInt(10000)), "UTF-8");
	}
	
	/**
	 * @Description： 解析Map
	 * @author: lijiafu
	 * @since: 2018年6月8日 下午6:56:22
	 */
	public static SortedMap<Object,Object> getMapParams(Map<String, String> m){
		//过滤空 设置 TreeMap
	    SortedMap<Object,Object> packageParams = new TreeMap<Object,Object>();        
	    Iterator it = m.keySet().iterator();  
	    while (it.hasNext()) {  
	        String parameter = (String) it.next();  
	        String parameterValue = m.get(parameter);  
	        String v = "";  
	        if(null != parameterValue) {  
	            v = parameterValue.trim();  
	        }  
	        packageParams.put(parameter, v);  
	    }  
	    return packageParams;
	}
	
	/**
	 * 解析微信回调参数
	 * @return
	 * @throws IOException 
	 * @throws JDOMException 
	 */
	public static SortedMap<Object,Object> getWxPostParams(HttpServletRequest req) throws Exception{
		
		//读取参数  
        InputStream inputStream = req.getInputStream();  
        StringBuffer sb = new StringBuffer();  
        String s ;  
        BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));  
        while ((s = in.readLine()) != null){  
            sb.append(s);  
        }
        in.close();  
        inputStream.close();  
        
        //解析xml成map  
        Map<String, String> m = new HashMap<String, String>();  
        System.out.println("微信返回xml="+sb.toString());
        //m = XMLUtil.doXMLParse(sb.toString());  
          
        //过滤空 设置 TreeMap
        SortedMap<Object,Object> packageParams = getMapParams(m);
		
		return packageParams;
	}
	
	/**
	 * @author
	 * @date 2016-4-22
	 * @Description：sign签名
	 * @param characterEncoding
	 *            编码格式
	 * @param parameters
	 *            请求参数
	 * @return
	 */
	public static String createSign(String characterEncoding, SortedMap<Object, Object> packageParams, String API_KEY) {
		StringBuffer sb = new StringBuffer();
		Set es = packageParams.entrySet();
		Iterator it = es.iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			String k = (String) entry.getKey();
			String v = (String) entry.getValue();
			if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) {
				sb.append(k + "=" + v + "&");
			}
		}
		sb.append("key=" + API_KEY);
		String sign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toUpperCase();
		return sign;
	}
	
	
	/**
	 * @author
	 * @date 2016-4-22
	 * @Description：将请求参数转换为xml格式的string
	 * @param parameters
	 *            请求参数
	 * @return
	 */
	public static String getRequestXml(SortedMap<Object, Object> parameters) {
		StringBuffer sb = new StringBuffer();
		sb.append("<xml>");
		Set es = parameters.entrySet();
		Iterator it = es.iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			String k = (String) entry.getKey();
			String v = (String) entry.getValue();
			if ("attach".equalsIgnoreCase(k) || "body".equalsIgnoreCase(k) || "sign".equalsIgnoreCase(k)) {
				sb.append("<" + k + ">" + "<![CDATA[" + v + "]]></" + k + ">");
			} else {
				sb.append("<" + k + ">" + v + "</" + k + ">");
			}
		}
		sb.append("</xml>");
		return sb.toString();
	}
	
 
	/**  
     * 将分为单位的转换为元 （除100）  
     *   
     * @param amount  
     * @return  
     * @throws Exception   
     */    
    public static String changeF2Y(String amount){    
        return BigDecimal.valueOf(Long.valueOf(amount)).divide(new BigDecimal(100)).toString();    
    }    
    
}
